package com.imay.live.update;

import android.Manifest;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.imay.cocos.IMayCocos;
import com.imay.live.IMApplication;
import com.imay.live.R;
import com.imay.live.activity.BasePermissionActivity;
import com.imay.live.activity.PermissionsGrantActivity;
import com.imay.live.helper.DialogFragmentHelper;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/05/16 0016.
 */

public class CheckUpdateApp {
    private final String ApkType = "application/vnd.android.package-archive";
    public static final String AUTHORITY = "com.imay.live.provider";
    private File tempfile;
    UpdateAppFragment updateAppFragment;

    public boolean updateDialogShowing;

    public UpdateAppFragment getUpdateAppFragment() {
        return updateAppFragment;
    }

    /**
     * 升级弹窗
     */
    public boolean showDialog(Context context, FragmentManager fragmentManager) {
        if (IMayCocos.getInstance().getAppUpdateModel() != null && !updateDialogShowing) {
            showdialog(fragmentManager, IMayCocos.getInstance().getAppUpdateModel());
            IMayCocos.getInstance().setAppUpdateModel(null);
            updateDialogShowing = true;
            return true;
        }
        return false;
    }

    private void showdialog(FragmentManager fragmentManager, AppUpdateModel appUpdateModel) {
//        Intent intent = new Intent();
//        intent.setClass(context, ThirdActivity.class);
//        intent.putExtra(UpdateAppFragment.TITLE, appUpdateModel);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(intent);


        Bundle bundle = new Bundle();
        if (appUpdateModel == null) {
            return;
        }
        if (updateAppFragment == null)
            updateAppFragment = UpdateAppFragment.newInstance();
        bundle.putParcelable(UpdateAppFragment.TITLE, appUpdateModel);
        updateAppFragment.setArguments(bundle);
        DialogFragmentHelper.showDialogFragment(fragmentManager, updateAppFragment);


    }

    private int getversionCode(Context ctx) {
        int currentVersionCode = 0;
        PackageManager manager = ctx.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
            String appVersionName = info.versionName; // 版本名
            currentVersionCode = info.versionCode; // 版本号
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return currentVersionCode;
    }

    private String getDiskCacheDir() {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = IMApplication.getInstance().getExternalCacheDir().getPath();
        } else {
            cachePath = IMApplication.getInstance().getCacheDir().getPath();
        }
        return cachePath;
    }

    private File getFile(String name) {
        return new File(getDiskCacheDir() + File.separator + name);
    }

    //"https://iosapp.imay.cn/imay_live.apk"
    private void down(Context context, String url, String versionId) {
        if (!PermissionsGrantActivity.checkAllPermissionsGranted(IMApplication.getInstance(), new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
                ) {
            return;
        }
        if (TextUtils.isEmpty(url)) {
            return;
        }
        tempfile = getFile("temp");

        String name;
        int i = url.lastIndexOf("/");
        int e = url.lastIndexOf(".");
        if (i > -1 && e > -1) {
            name = versionId + url.substring(i + 1);
        } else {
            name = versionId + "vanka.apk";
        }
        UpdateService.Builder.create(url)
                .setStoreDir("update")
                .setIsSendBroadcast(true)
                .setDownloadSuccessNotificationFlag(Notification.DEFAULT_SOUND)
                .setDownloadErrorNotificationFlag(Notification.DEFAULT_SOUND)
                .setFileName(name)
                .setIcoResId(R.mipmap.app_launcher)
                .build(context);

        /*final File file = getFile(name);
        if (file.exists() && file.length() > 1024) {
            install(context, file);
            return;
        }*/


        //downAsynFile(context, url, file);
    }

    private void downAsynFile(final Context context, String url, final File file) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(tempfile);
                    byte[] buffer = new byte[1024];
                    long total = response.body().contentLength();

                    int len = 0;
                    long sum = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                    }
                    fileOutputStream.flush();

                    tempfile.renameTo(file);
                    install(context, file);

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dialog_ok: {//升级下载
                down(view.getContext(), updateAppFragment.getAppUpdateModel().getUrl(), updateAppFragment.getAppUpdateModel().getVersionId());
                if (updateAppFragment != null) {
                    updateAppFragment.dismissAllowingStateLoss();
                }
                updateDialogShowing = false;
                break;
            }
            case R.id.dialog_cancle: {//升级拒绝
                if (updateAppFragment != null) {
                    updateAppFragment.dismissAllowingStateLoss();
                }
                updateDialogShowing = false;
                break;
            }
        }
    }

    private void install(Context context, File file) {
        ApplicationInfo appinfo = context.getApplicationInfo();
        int targetSDK = appinfo.targetSdkVersion;
        if (targetSDK >= 24 && Build.VERSION.SDK_INT >= 24) {
            Uri uri = FileProvider.getUriForFile(context, AUTHORITY, file);
            if (uri == null) {
                return;
            }
            Intent i =
                    new Intent(Intent.ACTION_INSTALL_PACKAGE)
                            .setDataAndType(uri,
                                    ApkType)
                            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            PackageManager packageManager = context.getPackageManager();
            List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(i, PackageManager.GET_ACTIVITIES);
            if (resolveInfos == null || resolveInfos.size() == 0) {
                return;
            }
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        } else {
            Intent it = new Intent(Intent.ACTION_VIEW);
            Uri pkg_uri = Uri.fromFile(file);
            it.setDataAndType(pkg_uri, "application/vnd.android.package-archive");
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(it);
        }
    }

//    public void checkUpdate() {
//        final int code = getversionCode(activity);
//        url = "https://iosapp.imay.cn/imay_live.apk";
//        versioncode = 2;
//        ProtoRequestHelper.task(ProtoHttpFactory.getRoomSuggest(0, 10)).setTag(this.hashCode()).request(new ProtoCallBack() {
//            @Override
//            public void onRequestSuccess(String command, String data) {
//                try {
//                    Result<ArrayList<RoomInfoModel>> result = JSON.parseObject(data, new TypeReference<Result<ArrayList<RoomInfoModel>>>() {
//                    }.getType());
//                    if (result.result == CodeSuccess && result.data != null) {
//                        if (code > 0) {
////                            url = "https://iosapp.imay.cn/imay_live.apk";
////                            versioncode = 2;
////                            showdialog();
//                        }
//
//                    } else {
//
//                    }
//
//                } catch (Exception e) {
//                }
//            }
//
//            @Override
//            public void onRequestError(String command, int code, String message) {
//            }
//        });
//
//    }


}
